﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookStore.Models;
using System.Text;

namespace BookStore.Controllers
{
    public class SearchController : Controller
    {
        public MVC3BookStoreEntities BookStoreEntities { get; set; }
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (BookStoreEntities == null) BookStoreEntities = new MVC3BookStoreEntities();
            base.Initialize(requestContext);
        }

        public ActionResult Index(int? CatID)
        {
            int Category = CatID ?? 0;
            ViewBag.Model = from Bk in BookStoreEntities.Books
                            where Bk.CategoryID == Category
                            select Bk;
            var Cat = BookStoreEntities.Categories.Where(ct => ct.ID == Category).FirstOrDefault();
            ViewBag.Category = (Cat==null) ? string.Empty : Cat.CategoryName;

            
            return View();
        }

        public ContentResult Books(string q, int limit)
        {
            StringBuilder responseContentBuilder = new StringBuilder();
            var products = (from Bk in BookStoreEntities.Books
                            where Bk.BookName.Contains(q)
                            select Bk).Distinct().Take(limit);
            foreach (var Bk in products)
                responseContentBuilder.Append(String.Format("{0}|{1}\n", Bk.ID, Bk.BookName));
            return Content(responseContentBuilder.ToString());

        }
        public ActionResult Search(String Search)
        {
            Category Cat = null;
             
            var Books = from Bk in BookStoreEntities.Books
                        where Bk.BookName.Contains(Search)
                            select Bk;
            if (Books.Count() > 0)
            {
                ViewBag.Model = Books;
                Cat = BookStoreEntities.Categories.Where(ct => Books.FirstOrDefault().CategoryID == ct.ID).FirstOrDefault();
            }
            ViewBag.Category = (Cat == null) ? string.Empty : Cat.CategoryName;
            return View("Index");
        }
    }
}
